#include "Port/display.h"

static const uint16_t screenWidth  = 240;
static const uint16_t screenHeight = 320;

static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf[ screenWidth * screenHeight / 2 ];

TFT_eSPI tft = TFT_eSPI(screenWidth, screenHeight);

void disp_flush( lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p )
{
    uint32_t w = ( area->x2 - area->x1 + 1 );
    uint32_t h = ( area->y2 - area->y1 + 1 );
    tft.setAddrWindow( area->x1, area->y1, w, h );
    tft.startWrite();
    tft.pushColors( ( uint16_t * )&color_p->full, w * h, true );
    tft.endWrite();
    lv_disp_flush_ready( disp );
}

void Display::Init(uint8_t rotation)
{
    tft.begin(); /* TFT init */
    tft.setRotation(rotation);
    tft.fillScreen(TFT_BLACK);
    tft.writecommand(ST7789_DISPON);

    lv_init();
    lv_disp_draw_buf_init( &draw_buf, buf, NULL, screenWidth * screenHeight / 2 );

    /*Initialize the display*/
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init( &disp_drv );
    disp_drv.hor_res = screenWidth;
    disp_drv.ver_res = screenHeight;
    disp_drv.flush_cb = disp_flush;
    disp_drv.draw_buf = &draw_buf;
    lv_disp_drv_register( &disp_drv );

    // ledcSetup(0, 5000, 10);
	// ledcAttachPin(2, 0);
	// ledcWrite(0, 1024);

    pinMode(2, OUTPUT);
    digitalWrite(2, HIGH);
}